package com.zrf.base.knowledge.geekbang.spring.ioc.java.beans;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyEditorSupport;
import java.util.stream.Stream;

/**
 * {@link java.beans.BeanInfo} 示例
 *
 * @author zhouruifeng
 * @date 7.6.20
 */
public class BeanInfoDemo {

    public static void main(String[] args) throws IntrospectionException {
        //stop class object
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class);
        Stream.of(beanInfo.getPropertyDescriptors()).forEach(propertyDescriptor -> {
            // propertyDescriptor允许添加属性编辑器-PropertyEditor
            // GUI -> text(String) -> PropertyType
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            String propertyName = propertyDescriptor.getName();
            if ("age".equals(propertyName)) {
                //为age字段/属性增加propertyEditor
                propertyDescriptor.setPropertyEditorClass(StringToIntegerPropertyEditor.class);
            }
            System.out.println(propertyDescriptor);
        });
    }

    static class StringToIntegerPropertyEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            Integer i = Integer.parseInt(text);
            setValue(i);
        }
    }
}
